// console.log(`✅ ${__filename} 加载成功 - ${new Date().toISOString()}`);
console.log(`✅ 数据库用户模块-加载成功 - ${new Date().toISOString()}`);

// const pool = require('../config/mysql_db');
let poolPromise = require('../config/mysql_db'); // 引入Promise包装的连接池
//  const NOW_DATE_Util = require('../utils/now_date');
class users_Model{
  static async login(account, password) {
    let sql = 'SELECT * FROM users WHERE user_account = ? AND user_password = ?'
    try {
        // 等待连接池Promise解析
      const pool = await poolPromise;
        // 使用参数化查询防止SQL注入
        const [rows] = await pool.query(
            sql,
            [account, password]
        );
        
        if (rows.length > 0) {
            console.log('✅ 账号'+account+'登录成功--',new Date().toISOString());
            return { 
                success: true, 
                message: "登录成功",
                user: rows[0] 
            };
        } else {
            return { 
                success: false, 
                message: "账号或密码错误" 
            };
        }

    } catch (error) {
        console.log('❌ 账号'+account+'登录失败--',new Date().toISOString());
        console.error("登录数据库查询错误:", error);
        // let now_date = NOW_DATE_Util.getFormattedDateTime()
        // let server_logData = {
        //     user_account: account,
        //     user_name: '普通用户',
        //     date: now_date,
        //     sql_log: sql ,
        //     sqlMessage_log:error,
        //     userupdata:account+'&'+password
        // }
        // server_log.Write_server_log_to_JSON('../utils/server_log.json', server_logData);
        // server_log.Write_server_log_to_DB(server_logData);
        return { 
            success: false, 
            message: "数据库查询错误" 
        };
    }
  }




  static async register(account, password, name, register_time, recently) {
    let sql = 'INSERT INTO users (user_account, user_password, user_name, register_time, recently) VALUES (?, ?, ?, ?, ?)'
    try {
        // 检查账号是否已存在
        // 等待连接池Promise解析
      const pool = await poolPromise;
        const [existingUsers] = await pool.query(
            'SELECT user_account FROM users WHERE user_account = ?',
            [account]
        );
        
        if (existingUsers.length > 0) {
            return { 
                success: false, 
                message: "该账号已被注册" 
            };
        }

        // 使用参数化查询防止SQL注入
        // 注意：字段顺序和参数顺序要匹配
        
        const [result] = await pool.query(
            sql,
            [account, password, name, register_time, recently]
        );
        
        // INSERT操作返回的是结果对象，不是行数据
        if (result.affectedRows > 0) {
            // 获取刚插入的用户信息
            const [newUserRows] = await pool.query(
                'SELECT * FROM users WHERE user_account = ?',
                [result.insertId]
            );
            console.log('✅ 账号'+account+'注册成功--',new Date().toISOString());
            return { 
                success: true, 
                message: "注册成功",
                user: newUserRows[0] 
            };
        } else {
            return { 
                success: false, 
                message: "注册失败，无法创建用户" 
            };
        }
    } catch (error) {
        console.log('❌ 账号'+account+'注册失败--',new Date().toISOString());
        console.error("数据库注册查询错误:", error);
        // let now_date = NOW_DATE_Util.getFormattedDateTime()
        // let server_logData = {
        //     user_account: account,
        //     user_name: name,
        //     date: now_date,
        //     sql_log: sql ,
        //     sqlMessage_log:error,
        //     userupdata:account+'&'+password+'&'+name+'&'+register_time+'&'+recently
        // }
        // server_log.Write_server_log_to_JSON('../utils/server_log.json', server_logData);
        // server_log.Write_server_log_to_DB(server_logData);

        // 根据错误类型提供更具体的错误信息
        let errorMessage = "账号已被注册";
        // if (error.code === 'ER_DUP_ENTRY') {
        //     errorMessage = "账号已被注册";
        // }
        return { 
            success: false, 
            message: errorMessage 
        };

        
    }
  }




  // 获取所有用户信息
  static async getAll_users() {
    let sql = 'SELECT * FROM users'
    try{
        // 等待连接池Promise解析
      const pool = await poolPromise;
        const [rows] = await pool.query(sql);
        console.log('✅ 获取所有用户信息成功--',new Date().toISOString());
        return rows;
    } catch(error){
        console.log('❌ 获取所有用户信息失败--',new Date().toISOString());
        console.error('获取所有用户信息：', error);
        // let now_date = now_date.getFormattedDateTime()
        // let server_logData = {
        //     user_account: 0,
        //     user_name: '系统',
        //     date: now_date,
        //     sql_log: sql ,
        //     sqlMessage_log:error,
        //     userupdata:'无数据'
        // }
        // server_log.Write_server_log_to_JSON('../utils/server_log.json', server_logData);
        // server_log.Write_server_log_to_DB(server_logData);
    }
    
  }
 
  // 根据账号获取用户信息
  static async getUser(userAccount) {
    let sql = 'SELECT * FROM users WHERE user_account = ?'
    try{
        // 等待连接池Promise解析
      const pool = await poolPromise;
        const [rows] = await pool.query(sql, [userAccount]);
        console.log('✅ 账号'+userAccount+'获取用户信息成功--',new Date().toISOString());
        return rows[0]; // 返回单条记录
    } catch(error){
        console.log('❌ 账号'+userAccount+'获取用户信息失败--',new Date().toISOString());
        console.error('根据账号获取用户信息：', error);
        // let now_date = now_date.getFormattedDateTime()
        // let server_logData = {
        //     user_account: 0,
        //     user_name: '系统',
        //     date: now_date,
        //     sql_log: sql ,
        //     sqlMessage_log:error,
        //     userupdata:'无数据'
        // }
        // server_log.Write_server_log_to_JSON('../utils/server_log.json', server_logData);
        // server_log.Write_server_log_to_DB(server_logData);
    }
  }
}
 
module.exports = users_Model;


